package com.yunmang.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.yunmang.R;
import com.yunmang.activity.FeedBackActivity;
import com.yunmang.activity.setting.SetingPwdActivity;
import com.yunmang.activity.setting.SettingActivity;
import com.yunmang.activity.setting.SwitchSetting;
import com.yunmang.app.AppConstant;
import com.yunmang.entity.UpdateVersionBean;
import com.yunmang.http.DownLoadApi;
import com.yunmang.http.DownloadProgressHandler;
import com.yunmang.http.HttpUtils;
import com.yunmang.http.ProgressHelper;
import com.yunmang.utils.CheckUtils;
import com.yunmang.utils.CommonUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.internal.Util;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;

/**
 * 作者 : bean on 2017/4/5/0005.
 * 注释 :设置
 */
public class SettingFragment extends BaseFragment {
    @InjectView(R.id.rl_set_printer)
    RelativeLayout rlSetPrinter;
    @InjectView(R.id.rl_set_pwd)
    RelativeLayout rlsetPwd;
    @InjectView(R.id.rl_set_common)
    RelativeLayout rlsetCommon;
    @InjectView(R.id.depname)
    TextView depname;
    @InjectView(R.id.second_name)
    TextView secondName;
    @InjectView(R.id.icon_version)
    ImageView iconVersion;
    @InjectView(R.id.version_name)
    TextView versionName;
    @InjectView(R.id.rl_version)
    RelativeLayout rlVersion;
    @InjectView(R.id.rl_feed)
    RelativeLayout rlFeed;
    @InjectView(R.id.rl_about)
    RelativeLayout rlAbout;
    @InjectView(R.id.loginbutton)
    com.yunmang.view.LoadingButton loginbutton;

    private Subscriber<UpdateVersionBean> subscriber;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_setting;
    }

    @Override
    public void initView(View view) {
        ButterKnife.inject(this, view);
    }

    @Override
    public void initData() {
        depname.setText(AppConstant.orgInfo.getName());
        secondName.setText(CommonUtils.getTypeName(AppConstant.orgInfo.getType()));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
    private  int pos=0;
    @OnClick({R.id.loginbutton,R.id.exit, R.id.rl_set_printer, R.id.rl_set_pwd, R.id.rl_set_common, R.id.rl_version, R.id.rl_feed, R.id.rl_about})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.loginbutton:
                loginbutton.startLoading();
                break;
            case R.id.exit:
                getActivity().finish();
                break;
            case R.id.rl_set_printer:
                startActivity(new Intent(context, SettingActivity.class));
                break;
            case R.id.rl_set_pwd:
                startActivity(new Intent(context, SetingPwdActivity.class));
                break;
            case R.id.rl_set_common:
                startActivity(new Intent(context, SwitchSetting.class));
                break;
            case R.id.rl_version:
                if (!CheckUtils.isNetworkConnected(context)) {
                    showToast("当前网络连接不可用");
                    return;
                }
                checkversion();
                break;
            case R.id.rl_about:
                break;
            case R.id.rl_feed:
                startActivity(new Intent(context, FeedBackActivity.class));
                break;
        }
    }

    private void checkversion() {
        subscriber = new Subscriber<UpdateVersionBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(UpdateVersionBean updateVersionBean) {
                if (updateVersionBean.getCode() == 200) {
                    String version = updateVersionBean.getModel().getVersion();
                    String apkUrl = updateVersionBean.getModel().getApkUrl();
                    String baseUrl = updateVersionBean.getModel().getBaseUrl();
                    if (!CheckUtils.getVersion(context).equalsIgnoreCase(version)) {
                        showDialog(version, true, apkUrl, baseUrl);
                    } else {
                        showToast("当前为最新版本");
                    }
                } else {
                    showToast("获取版本信息失败");
                }
            }
        };
        HttpUtils.getInstance().checkVersion(subscriber);
    }

    private void showDialog(String v, boolean isUpgrade, final String apkurl, final String baseUrl) {

        new AlertView("发现新版本", "博特利华新版:" + v + " , 是否下载", isUpgrade ? null : "取消", new String[]{"确定"},
                null, getActivity(), AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                switch (position) {
                    case 0:
//                        context.startService(new Intent(context, UpdateService.class));
                        retrofitDownload(apkurl, baseUrl);
                        break;

                }
            }
        }).show();
    }


    private void retrofitDownload(String apkurl, String baseUrl) {
        //监听下载进度
        final ProgressDialog dialog = new ProgressDialog(context);
        dialog.setProgressNumberFormat("%1d KB/%2d KB");
        dialog.setTitle("下载");
        dialog.setMessage("正在下载，请稍后...");
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setCancelable(false);
        dialog.show();

        Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .callbackExecutor(new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
                        new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false)));
        OkHttpClient.Builder builder = ProgressHelper.addProgress(null);
        DownLoadApi retrofit = retrofitBuilder
                .client(builder.build())
                .build().create(DownLoadApi.class);

        ProgressHelper.setProgressHandler(new DownloadProgressHandler() {
            @Override
            protected void onProgress(long bytesRead, long contentLength, boolean done) {
                Log.e("是否在主线程中运行", String.valueOf(Looper.getMainLooper() == Looper.myLooper()));
                Log.e("onProgress", String.format("%d%% done\n", (100 * bytesRead) / contentLength));
                Log.e("done", "--->" + String.valueOf(done));
                dialog.setMax((int) (contentLength / 1024));
                dialog.setProgress((int) (bytesRead / 1024));

                if (done) {
                    dialog.dismiss();
                }
            }
        });

        Call<ResponseBody> call = retrofit.retrofitDownload(apkurl);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.e("Tag", Thread.currentThread().getName());
                try {
                    InputStream is = response.body().byteStream();
                    File file = new File(Environment.getExternalStorageDirectory(), "better.apk");
                    FileOutputStream fos = new FileOutputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(is);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = bis.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                        fos.flush();
                    }
                    fos.close();
                    bis.close();
                    is.close();
                    installApk(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

    }

    private void installApk(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        String type = "application/vnd.android.package-archive";
        intent.setDataAndType(Uri.fromFile(file), type);
        startActivity(intent);
        getActivity().finish();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.inject(this, rootView);
        return rootView;
    }
}
